// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const { log } = require('console')
const { FORMERR } = require('dns')
const uniID = require('uni-id-common')
const db = uniCloud.database()
const dbCmd = db.command
const adrsCollectionName = 'user-address'
const adrsCollection = db.collection(adrsCollectionName)
module.exports = {
	_before: function () { // 通用预处理器
		const clientInfo = this.getClientInfo()
		this.uniID = uniID.createInstance({ 
			clientInfo
		})
	},
	/**
	 * 查询地址
	 * @param {string} user_id 用户id
	 */
	async get(params) {
		const {uid} = await this.uniID.checkToken(this.getUniIdToken());
		if(!uid){
			return {
				errCode: 1,
				errMsg: '非法请求',
			}
		}
		let {data,affectedDocs} = await adrsCollection.where({
			user_id: uid,
			...params
		}).get()
		
		return {
			errCode: 0,
			errMsg: '请求成功！',
			data: data
		}
	},
	/**
	 * 更新或添加地址
	 */
	async addOrUpdate(params) {
		const {uid} = await this.uniID.checkToken(this.getUniIdToken());
		if(!uid){
			return {
				errCode: 1,
				errMsg: '非法请求',
			}
		}
		if(params.is_default) {
			await adrsCollection.where({
				user_id: uid
			}).update({
				is_default: 0
			})
		}
		// 如果id有，则是更新
		if (params._id) {
			let data = JSON.parse(JSON.stringify(params))
			delete data._id
			return await adrsCollection.where({
				_id: params._id
			}).update(data).then(res => {
				return {
					errCode: 0,
					errMsg: '更新成功'
				}
			}).catch(()=>{
				return {
					errCode: 1,
					errMsg: '更新失败'
				}
			})
		} else{
			let data = {
				...params,
				user_id: uid
			}
			let { id } = await adrsCollection.add(data)
			if(id){
				return {
					errCode: 0,
					errMsg: '添加成功'
				}
			} else {
				return {
					errCode: 1,
					errMsg: '添加失败'
				}
			}
		}
	},
	/**
	 * 删除地址
	 */
	async remove(params) {
		const {uid} = await this.uniID.checkToken(this.getUniIdToken());
		if(!uid){
			return {
				errCode: 1,
				errMsg: '非法请求',
			}
		}
		if (params._id) {
			let { errCode, deleted } = await adrsCollection.where({
				_id: params._id
			}).remove()
			if(deleted){
				return {
					errCode: 0,
					errMsg: '删除成功'
				}
			} else {
				return {
					errCode: 1,
					errMsg: '删除失败'
				}
			}
		} else{
			return {
				errCode: 1,
				errMsg: '删除id不能为空'
			}
		}
	}
}
